class Game {
    constructor(images, runCallback){
        this.keys = {}
        this.actions = {}
        this.keyDown = {}
        this.images = images 
        this.scene = null
        this.runCallback = runCallback
        this.canvas = document.getElementById("canvas")
        this.ctx = canvas.getContext("2d") 

        window.addEventListener("keydown", event => {
            this.keyDown[event.code] = true
        })
        window.addEventListener("keyup", event => {
            this.keyDown[event.code] = false
        })

        //载入所有图片资源
        this.init()
    }

    init () {
        var g = this
        var loads = []
        var names = Object.keys(g.images)
        for (let i = 0; i < names.length; i++){
            let name = names[i]
            let img = new Image()
            img.src = g.images[name] 
            img.onload = function(){
                loads.push(1)
                g.images[name] = img
                if (loads.length == names.length){
                    g.__start()
                }
            }

        }
    }

    registerActions (key, callback){
        this.actions[key] = callback
    }

    static instance(...args) {
        this.i = this.i || new this(...args)
        return this.i
     }

    act () {
        var g = this
        var keys = []
        keys = Object.keys(g.actions)
        for (var i = 0; i < keys.length; i ++){
            if (g.keyDown[keys[i]]){
                g.actions[keys[i]]()
            }
        }
    }        
    drawImage (img){
        this.ctx.drawImage(img.img, img.x, img.y)
    }
    drawbg (img){
        var g = this
        g.ctx.drawImage(img.img, img.x, img.y, g.canvas.width, g.canvas.height)
    }
    update (){
        this.scene.update()
    } 
    draw (){
        this.scene.draw()
    }   

    runloop (){
        var g = this
        g.update()

        g.act()
        g.ctx.clearRect(0, 0, g.canvas.width, g.canvas.height)
        g.draw()
        
        setTimeout(function(){
            g.runloop()
        }, 1000/myUtils.fps)
    }

    imgByName (name){
        var g = this
        var img = g.images[name]
        var image = {
            img : img,
            w : img.width,
            h : img.height,
        }
        return image
    }

    replaceScene (scene){
        this.scene = scene
    }

    runWithScene (scene){
        var g = this
        g.scene = scene
        setTimeout(function(){
            g.runloop()
        }, 1000/myUtils.fps)
    }
    // 开始游戏
    __start (){
        this.runCallback()
    }
}